package net.sourceforge.peertwitter.simulation;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import net.sourceforge.peertwitter.chain.EventChainImpl;
import net.sourceforge.peertwitter.core.PeerTwitterImpl;
import net.sourceforge.peertwitter.core.events.Event;
import net.sourceforge.peertwitter.core.messaging.TweetMessage;
import rice.p2p.commonapi.NodeHandle;

public class MessagePoolImpl extends EventChainImpl <Event> implements MessagePool {
	private Map <TweetMessage, Set<PeerTwitterImpl>> receivers = new HashMap<TweetMessage, Set<PeerTwitterImpl>>();
	private int total = 0;
	private final Set<PeerTwitterImpl> nodes = new HashSet<PeerTwitterImpl>();
	private int received = 0;
	
//	public void addNode(PeerTwitterImpl pt) {
//		nodes.add(pt);
//	}

	public void printStats() {
		int nonReceived = 0;
		for (TweetMessage tweet: receivers.keySet()) {
			nonReceived += receivers.get(tweet).size();
		}
		System.out.println("Expected receivers: " + total + ", received: " + received + ", misses: " + (total-received));
		
//		for (TweetMessage tm : receivers.keySet()) {
//			for (PeerTwitter node: receivers.get(tm)) {
//				System.out.println(node + " didn't receive + " +tm);
//			}
//			
//		}
	//	System.out.println("Total received: " + received + " %" + (nonReceived/(nonReceived+received)) * 100);
	}
	
	/* (non-Javadoc)
	 * @see net.sourceforge.peertwitter.simulation.IMessagePool#register(net.sourceforge.peertwitter.core.messaging.TweetMessage)
	 */
	
	
	@Override
	public void register(TweetMessage tm) {
		Set<PeerTwitterImpl> followers = new HashSet<PeerTwitterImpl>();
		receivers.put(tm, followers);
		
		System.out.println("register: " + tm);
		for (PeerTwitterImpl node: nodes) {
			if (node.follows(tm.getGroup())) {
				followers.add(node);
				total++;
			}
		}
	}

	@Override
	public void addNode(NodeHandle nh) {
	}

	
	@Override
	public void deliver(Event event) {
		
	}


//	@Override
//	public void receiveUpdate(Message message) {
//		if (message instanceof TweetMessage) {
//			if (receivers.get(message).size() > 0 ) {
//				Iterator<PeerTwitterImpl> iterator = receivers.get(message).iterator();
//				iterator.next();
//				iterator.remove();
//				received++;
//			}
//		}
//	}
	
}
